package com.itboye.shop.category.store;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.EditText;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.itboye.shop.FragmentShopcart;
import com.itboye.shop.R;
import com.itboye.shop.base.BaseDialogFragment;
import com.itboye.shop.bean.GoodsDetailBean;
import com.itboye.shop.bean.ShopCarBean;
import com.itboye.shop.common.FlowLayout;
import com.itboye.shop.common.XScrollView;
import com.itboye.shop.me.LoginActivity;
import com.itboye.shop.net.DensityUtil;
import com.itboye.shop.net.ResultEntity;
import com.itboye.shop.presenter.UserPresenter;
import com.itboye.shop.util.helper.ImageLoader;
import com.itboye.shop.util.loadutil.Const;
import com.itboye.shop.util.loadutil.MAlert;
import com.itboye.shop.util.loadutil.SPUtils;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.ObjectAnimator;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import static com.itboye.shop.base.BaseActivity.EVENT_TYPE_UNKNOWN;

/**
 * Created by admin on 2017/2/8.
 */

@SuppressLint("ValidFragment")
public class JiaRuGouWuCheDialog extends BaseDialogFragment implements Observer {
    View close;
    TextView jiege;
    TextView kucun;
    ViewGroup guigeContainer;
    View ok;
    GoodsDetailBean goodsDetailBeans;
    View jian;
    View jia;
    EditText input;
    boolean isLiJIGouMai;
    ViewGroup container;
    String imgUrl;
    protected String price;
    protected String skuId;

    private FlowLayout flowLayout;
    ArrayList<FlowLayout> arFlowLayout = new ArrayList<>();
    TextView txt_price;
    private String tempSkuId;
    TextView goods_guige;
    UserPresenter userPresenter;
    SimpleDraweeView pic;
    private String guigeId;

    public JiaRuGouWuCheDialog() {

    }

    public JiaRuGouWuCheDialog(GoodsDetailBean goodsDetailBeans,
                               boolean isLiJIGouMai) {

        this.goodsDetailBeans = goodsDetailBeans;
        this.isLiJIGouMai = isLiJIGouMai;
        userPresenter = new UserPresenter(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        return inflater.inflate(
                R.layout.dialog_add_shopcart, null);
    }


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {

        super.onActivityCreated(savedInstanceState);

//            if (savedInstanceState != null) {
//                goodsDetailBeans = (GoodsDetailBean) savedInstanceState
//                        .getSerializable("goodsDetailBeans");
//                isLiJIGouMai = savedInstanceState.getBoolean("isLiJIGouMai");
//            }


        //      String json = "{\"secondary_headlines\": \"美孚机油看K346\",\"main_img\": \"654\",\"has_receipt\": \"0\",\"under_guaranty\": \"0\",\"support_replace\": \"1\",\"total_sales\": \"346\",\"view_cnt\": \"567\",\"consignment_time\": \"7\",\"contact_name\": \"张三\",\"contact_way\": \"136567546657\",\"expire_time\": \"3999999999\",\"favorite_cnt\": \"634\",\"uid\": \"12\", \"place_origin\": \"商品产地\",\"product_code\": \"P234576\",\"goods_unit_name\": \"台\",\"sku_pkid\": \"1\",\"dt_goods_unit\": \"001\",\"id\": \"1\",\"name\": \"美孚机油\",\"onshelf\": \"1\",\"store_id\": \"12\",\"weight\": \"34.00\",\"synopsis\": \"商品简介:美孚机油\",\"secondary\": \"美孚机油看K346\",\"template_id\": \"0\",\"loc_country\": \"\",\"loc_province\": \"\",\"loc_city\": \"\",\"loc_address\": \"\",\"cate_id\": \"2\",\"update_time\": \"1483691960\",\"sku_list\": [{\"sku_pkid\": \"1\",\"sku_id\": \"\",\"sku_desc\": \"\",\"ori_price\": \"35000\",\"price\": \"36000\",\"quantity\": \"300\",\"product_code\": \"75325\",\"icon_url\": \"\",\"price3\": \"0\",\"price2\": \"0\",\"cnt1\": \"0\",\"cnt2\": \"0\",\"cnt3\": \"0\"}],\"sku_info\": [{\"sku_id\":\"12\",\"sku_name\":\"mingzi\",\"value_list\":[{\"value_id\":\"one\",\"value_name\":\"呵呵\"}]},{\"sku_id\":\"12\",\"sku_name\":\"mingzi\",\"value_list\":[{\"value_id\":\"two\",\"value_name\":\"呵呵2\"},{\"value_id\":\"two\",\"value_name\":\"呵呵3\"}]},{\"sku_id\":\"12\",\"sku_name\":\"mingzi\",\"value_list\":[{\"value_id\":\"one\",\"value_name\":\"呵呵\"}]},{\"sku_id\":\"12\",\"sku_name\":\"mingzi\",\"value_list\":[{\"value_id\":\"two\",\"value_name\":\"呵呵2\"},{\"value_id\":\"two\",\"value_name\":\"呵呵3\"}]}],\"business_status\": \"0\",\"carousel_images\":[\"654\",\"654\",\"652\",\"651\",\"714\",\"712\"],\"is_fav\": \"0\"}";
        //    goodsDetailBeans = (GoodsDetailBean) new Gson().fromJson(json, GoodsDetailBean.class);
        imgUrl = goodsDetailBeans.getMain_img();
        setImage(goodsDetailBeans.getSku_list().get(0).getIcon_url());
        setPrice(goodsDetailBeans.getSku_list().get(0).getPrice());
        guigeId=goodsDetailBeans.getSku_list().get(0).getSku_pkid();
//            txt_price.setText(Double.parseDouble(goodsDetailBeans.getSku_list().get(0).getPrice())/100+"");

        if (goodsDetailBeans.getSku_info().size() <= 0) {//没有规格

        } else {//有规格

        }
        addGuiGe();
//                } else {// 单规格
//                    ((View) kucun.getParent()).setVisibility(View.VISIBLE);
//                    if (goodsDetailBeans.getSkuInfo() != null) {
//                        kucun.setText(goodsDetailBeans.getRemain() + "");
//                    }
//                }
//            }
        pic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MAlert.alert(selectedGuige());
            }
        });
        jia.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String s = input.getText().toString();
                try {
                    int c = Integer.parseInt(s);
                    input.setText(c + 1 + "");
                } catch (NumberFormatException e) {
                    input.setText("1");
                }
                input.setSelection(input.getText().length());
            }
        });
        jian.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                String s = input.getText().toString();
                try {
                    int c = Integer.parseInt(s);
                    if (c > 0) {
                        c--;
                    }
                    input.setText(c + "");
                } catch (NumberFormatException e) {
                    input.setText("0");
                }
                input.setSelection(input.getText().length());
            }
        });
        close.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                List<String> xuanzhong = selectedGuige();
                StringBuffer pkidTemp = new StringBuffer();
                StringBuffer stringBuffer = new StringBuffer();
                if (xuanzhong != null) {
                    for (String s1 : xuanzhong) {
                        stringBuffer.append(s1 + ";");
                        pkidTemp.append(s1 + ";");
                        tempSkuId = pkidTemp.toString();
                    }
                    if (xuanzhong.size() <= 0) {
                        tempSkuId = null;
                    }
                } else {
                    tempSkuId = null;
                }
                for (int i = 0; i < goodsDetailBeans.getSku_list().size(); i++) {
                    String sid = goodsDetailBeans.getSku_list().get(i).getSku_id();
                    String pkid = goodsDetailBeans.getSku_list().get(i).getSku_pkid();

                    if (sid.equals(stringBuffer.toString())) {
                        goods_guige.setText(goodsDetailBeans.getSku_list().get(i).getSku_desc());
                    }
                }
                closeDialog();
            }
        });
        ok.setOnClickListener(new View.OnClickListener() {
            public String pskuId;

            @Override
            public void onClick(View v) {
                String uid = SPUtils.get(getActivity(), null, Const.ID, "") + "";
                if (uid.equals("")) {
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                    return;
                }
                String s = checkGuiGeSelectedState();
                if (s == null) {
                    return;
                }
                List<GoodsDetailBean.SkuList> list = goodsDetailBeans
                        .getSku_list();
                for (GoodsDetailBean.SkuList skuCombinationBean : list) {
                    if (skuCombinationBean.getSku_id().equals(s)) {
                        pskuId = skuCombinationBean.getSku_id();
                        break;
                    }
                }
                ok.setEnabled(false);
                String num=input.getText().toString();
                if (num.equals("") || num.equals("0")||num.contains("-")) {
                    MAlert.alert("请输入有效数量");
                    return;
                }
//                showProgressDialog("正在添加中...", false);
                if (goodsDetailBeans.getSku_info().size() > 0) {//多规格
                    String guigeID = "";//规格id
                    List<String> xuanzhong = selectedGuige();
//                        String xz=xuanzhong.toString();
                    StringBuffer stringBuffer = new StringBuffer();
                    if (xuanzhong != null) {
                        for (String s1 : xuanzhong) {
                            stringBuffer.append(s1 + ";");
                        }
                    }
                    for (int i = 0; i < goodsDetailBeans.getSku_list().size(); i++) {
                        String sid = goodsDetailBeans.getSku_list().get(i).getSku_id();
                        String pkid = goodsDetailBeans.getSku_list().get(i).getSku_pkid();
                        if (sid.equals(stringBuffer.toString())) {
                            guigeID = pkid;
                        }
//                            String arr[] = sid.split(";");//sku_id
//                            String pkarr[] = pkid.split(";");//sku_pkid
//                            for (int j=0;j<arr.length;j++){
//                                String arrs=arr[j];
//                                if (arrs.equals(stringBuffer.toString())){
//                                    guigeID=pkarr[j];
//                                }
//                            }
                    }
                    if (isLiJIGouMai) {//先构建数据结构，传值
                        ArrayList<ShopCarBean> arrayGroup = new ArrayList<ShopCarBean>();
                        ShopCarBean shopCarBean=new ShopCarBean();
                        shopCarBean.setStore_name("虎头奔总店");
                        shopCarBean.setStore_logo("2");
                        List<ShopCarBean.GoodsEntity> goodsEntityList=new ArrayList<>();
                        ShopCarBean.GoodsEntity goodsEntity=new ShopCarBean.GoodsEntity();
                        goodsEntity.setName(goodsDetailBeans.getName());
                        goodsEntity.setCount(num);
                        goodsEntity.setPrice(price);
                        goodsEntity.setIcon_url(imgUrl);
                        goodsEntityList.add(goodsEntity);
                        shopCarBean.setGoods(goodsEntityList);
                        arrayGroup.add(shopCarBean);
                        Intent intent = new Intent(getActivity(),
                                QueRenDingDanNew.class);
                        intent.putExtra("isLiJiBuy",true);
                        intent.putExtra("list", arrayGroup);
                        intent.putExtra("guigeId",guigeId);
                        startActivity(intent);
//                        userPresenter.lijiGouMai(IsUtilUid.sId(),guigeID,input.getText().toString(),);
                    } else {
                        userPresenter.addMallAll(uid, goodsDetailBeans.getId(), guigeID, num);
                    }

                } else {//单规格
                    if (isLiJIGouMai) {
                        double totalPrice=0;
                        ArrayList<ShopCarBean> arrayGroup = new ArrayList<ShopCarBean>();
                        ShopCarBean shopCarBean=new ShopCarBean();
                        shopCarBean.setStore_name("虎头奔总店");
                        shopCarBean.setStore_logo("2");
                        List<ShopCarBean.GoodsEntity> goodsEntityList=new ArrayList<>();
                        ShopCarBean.GoodsEntity goodsEntity=new ShopCarBean.GoodsEntity();
                        goodsEntity.setName(goodsDetailBeans.getName());
                        goodsEntity.setCount(num);
                        goodsEntity.setPrice(goodsDetailBeans.getSku_list().get(0).getPrice());
                        goodsEntity.setP_id(goodsDetailBeans.getSku_list().get(0).getSku_pkid());
                        goodsEntity.setIcon_url(imgUrl);
                        goodsEntityList.add(goodsEntity);
                        shopCarBean.setGoods(goodsEntityList);
                        arrayGroup.add(shopCarBean);
                        totalPrice=Integer.parseInt(num)*Double.parseDouble(goodsDetailBeans.getSku_list().get(0).getPrice());
                        Intent intent = new Intent(getActivity(),
                                QueRenDingDanNew.class);
                        intent.putExtra("price", totalPrice + "");
                        intent.putExtra("isLiJiBuy",true);
                        intent.putExtra("guigeId",guigeId);
                        intent.putExtra("list", arrayGroup);
                        startActivity(intent);
                    }else {
                        userPresenter.addMallAll(uid, goodsDetailBeans.getId(), goodsDetailBeans.getSku_pkid(), num);
                    }
                }
                dismiss();
            }
        });
    }

    private void setImage(String icon_url) {
        ImageLoader.loadImage(pic, Const.IMAGE_HEAD + goodsDetailBeans.getMain_img());
    }

    private void setPrice(String price) {
        txt_price.setText(Double.parseDouble(goodsDetailBeans.getSku_list().get(0).getPrice()) / 100 + "元/" + goodsDetailBeans.getGoods_unit_name());
    }

    public ResultEntity handlerError(Object data) {
        ResultEntity result = (ResultEntity) data;
        if (result == null) {
            result = new ResultEntity("-1", "数据格式错误!~", data);
            return result;
        }

        if (result.hasError()) {
            MAlert.alert(result.getMsg());
            result.setEventType(EVENT_TYPE_UNKNOWN);
            return result;
        }
        return result;
    }

    protected String checkGuiGeSelectedState() {

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < guigeContainer.getChildCount(); i++) {
            View vv = guigeContainer.getChildAt(i);
            if (!(vv instanceof FlowLayout)) {
                continue;
            }
            FlowLayout flowLayout = (FlowLayout) vv;
            int j;
            for (j = 0; j < flowLayout.getChildCount(); j++) {
                TextView textView = (TextView) flowLayout.getChildAt(j);
                if (textView.isSelected()) {
                    sb.append(textView.getTag() + ";");
                    break;
                }
            }
            if (j == flowLayout.getChildCount()) {
//                    Toast.makeText(
//                            getContext(),
//                            "请选择"
//                                    + goodsDetailBeans.getSkuName().get(i / 2)
//                                    .getId(), 1).show();
                return null;
            }
        }
        return sb.toString();
    }


    //规格
    private void addGuiGe() {

        List<GoodsDetailBean.SkuInfo> list = goodsDetailBeans
                .getSku_info();
        for (int i = 0; i < list.size(); i++) {
            GoodsDetailBean.SkuInfo skuBean = list.get(i);
            TextView title = createTitle(skuBean.getSku_name());
            guigeContainer.addView(title);

            flowLayout = createFlowLayout(skuBean.getSku_id(),
                    goodsDetailBeans.getSku_info().get(i).getValue_list(),
                    "");
            arFlowLayout.add(flowLayout);
            guigeContainer.addView(flowLayout);
        }
        container.getViewTreeObserver().addOnGlobalLayoutListener(
                new ViewTreeObserver.OnGlobalLayoutListener() {

                    @SuppressWarnings("deprecation")
                    @Override
                    public void onGlobalLayout() {
                        try {
                            container.getViewTreeObserver()
                                    .removeGlobalOnLayoutListener(this);
                        } catch (Throwable e) {
                        }
                        if (container.getHeight() > DensityUtil
                                .screenHeigh() * 0.7) {

                            int h = DensityUtil.screenHeigh()
                                    - DensityUtil.dip2px(280);
                            XScrollView scrollView = new XScrollView(
                                    getContext());
                            scrollView.setLayoutParams(new ViewGroup.LayoutParams(
                                    ViewGroup.LayoutParams.MATCH_PARENT, h));

                            ViewGroup vg = (ViewGroup) guigeContainer
                                    .getParent();
                            vg.removeView(guigeContainer);

                            scrollView.addView(guigeContainer);
                            vg.addView(scrollView);
                        }
                    }
                });
    }

    private View.OnClickListener clickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (v.isSelected()) {
                v.setSelected(false);
                ((TextView) v).setTextColor(Color.BLACK);
                imgUrl = goodsDetailBeans.getMain_img();
                if ((!goodsDetailBeans.getMain_img().equals(""))
                        & goodsDetailBeans.getMain_img() != null) {
                    ImageLoader.loadImage(pic,
                            Const.imgurl + goodsDetailBeans.getMain_img());
                }
                return;
            }
            FlowLayout clickTextViewParent = null;
            StringBuilder stringBuilder = new StringBuilder();

            for (int i = 0; i < guigeContainer.getChildCount(); i++) {
                View view = guigeContainer.getChildAt(i);
                if (!(view instanceof FlowLayout)) {
                    continue;
                }
                FlowLayout flowLayout = (FlowLayout) view;
                if (v.getParent() == flowLayout) {
                    clickTextViewParent = flowLayout;
                    stringBuilder.append(v.getTag());
                    stringBuilder.append(";");

                } else {
                    for (int j = 0; j < flowLayout.getChildCount(); j++) {
                        View textview = flowLayout.getChildAt(j);
                        if (textview.isSelected()) {
                            stringBuilder.append(textview.getTag());
                            stringBuilder.append(";");
                            break;
                        }
                    }
                }
            }
            List<GoodsDetailBean.SkuInfo> skuList = goodsDetailBeans.getSku_info();
            String selectedSku = stringBuilder.toString();
            for (int i = 0; i < skuList.size(); i++) {
                String sku = skuList.get(i).getSku_id();
                for (int j = 0; j < clickTextViewParent.getChildCount(); j++) {
                    if (clickTextViewParent.getChildAt(j).isSelected()) {
                        clickTextViewParent.getChildAt(j).setSelected(false);
                        ((TextView) clickTextViewParent.getChildAt(j)).setTextColor(Color.BLACK);
                        break;
                    }
                }
                v.setSelected(true);
                ((TextView) v).setTextColor(Color.WHITE);
            }
            String s = isAllFenLeiSelected();
            if (s != null) {
//                        ((View) kucun.getParent()).setVisibility(View.VISIBLE);
                List<GoodsDetailBean.SkuList> list = goodsDetailBeans
                        .getSku_list();
                for (GoodsDetailBean.SkuList skuCombinationBean : list) {
                    if (skuCombinationBean.getSku_id().equals(s)) {
//                                kucun.setText(skuCombinationBean.getQuantity()
//                                        + "");
                        price = skuCombinationBean.getPrice();
                        imgUrl=skuCombinationBean.getIcon_url();
                        setPrice(price);
                        setImage(imgUrl);
                        break;
                    }
                }
            } else {
//                        ((View) kucun.getParent())
//                                .setVisibility(View.INVISIBLE);
            }
//                } catch (Exception e) {
//                    ByAlert.alert(e.getMessage());
//                    e.printStackTrace();
//                }
        }
    };

    private String isAllFenLeiSelected() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < guigeContainer.getChildCount(); i++) {
            View vv = guigeContainer.getChildAt(i);
            if (!(vv instanceof FlowLayout)) {
                continue;
            }
            FlowLayout flowLayout = (FlowLayout) vv;
            int j;
            for (j = 0; j < flowLayout.getChildCount(); j++) {
                TextView textView = (TextView) flowLayout.getChildAt(j);
                if (textView.isSelected()) {
                    sb.append(textView.getTag() + ";");
                    break;
                }
            }
            if (j == flowLayout.getChildCount()) {
                return null;
            }
        }
        return sb.toString();
    }

    /**
     * 当前已选中的规格集合
     *
     * @return
     */
    protected List<String> selectedGuige() {

        List<String> selectedGuige = new ArrayList<String>();
        for (int i = 0; i < guigeContainer.getChildCount(); i++) {
            View vv = guigeContainer.getChildAt(i);
            if (!(vv instanceof FlowLayout)) {
                continue;
            }
            FlowLayout flowLayout = (FlowLayout) vv;
            for (int j = 0; j < flowLayout.getChildCount(); j++) {
                TextView textView = (TextView) flowLayout.getChildAt(j);
                if (textView.isSelected()) {
                    selectedGuige.add((String) textView.getTag());
                }
            }
        }
        return selectedGuige;
    }

    private FlowLayout createFlowLayout(String vid, List<GoodsDetailBean.ValueList> id,
                                        String str) {
        int dis = DensityUtil.dip2px(5);
        FlowLayout flowLayout = new FlowLayout(getContext());
        for (int i = 0; i < id.size(); i++) {
            TextView textView = new TextView(getContext());
            textView.setTextColor(Color.BLACK);
            textView.setBackgroundResource(R.drawable.selector_guige);
            textView.setText(id.get(i).getValue_name());
            textView.setTag(vid + ":" + id.get(i).getValue_id());
            textView.setOnClickListener(clickListener);
            if (tempSkuId != null) {
                String[] strTemp = tempSkuId.split(";");
                for (String s : strTemp) {
                    if (s.equals(textView.getTag().toString())) {
                        textView.setSelected(true);
                    }
                }

            }
            ViewGroup.MarginLayoutParams marginLayoutParams = new ViewGroup.MarginLayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            marginLayoutParams.setMargins(dis, dis, dis, dis);
            textView.setLayoutParams(marginLayoutParams);
            flowLayout.addView(textView);
        }
        return flowLayout;
    }

    /**
     * 设置套餐一、套餐二等标题栏
     *
     * @param s
     * @return
     */
    private TextView createTitle(String s) {
        TextView textView = new TextView(getContext());
        textView.setText(s);
        textView.setTextColor(Color.BLACK);
        return textView;
    }

    public void closeDialog() {
        View v = getView().findViewById(R.id.container);
        ObjectAnimator animator = ObjectAnimator.ofFloat(v, "translationY",
                0, v.getHeight()).setDuration(300);
        animator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator arg0) {
            }

            @Override
            public void onAnimationRepeat(Animator arg0) {
            }

            @Override
            public void onAnimationEnd(Animator arg0) {
                dismiss();
            }

            @Override
            public void onAnimationCancel(Animator arg0) {
                dismiss();
            }
        });
        animator.start();
    }

    @Override
    public void update(Observable observable, Object data) {
        ResultEntity entity = handlerError(data);
        if (entity != null) {
            if (entity.getEventType() == UserPresenter.addAll_success) {
                MAlert.alert(entity.getData());
                Intent intent = new Intent(FragmentShopcart.changeCart);
                getActivity().sendBroadcast(intent);
            } else if (entity.getEventType() == UserPresenter.addAll_success) {
                MAlert.alert(entity.getData());
            }
        }
    }
//                @Override
//                public void onSaveInstanceState(Bundle arg0) {
//                    super.onSaveInstanceState(arg0);
//                    // arg0.putSerializable("goodsDetailBeans", goodsDetailBeans);
//                    // arg0.putBoolean("isLiJIGouMai", isLiJIGouMai);
//                }

}

